<template>
  <el-container class="scheduleedit">
    <el-form ref="form" :model="schedule_info" label-width="140px">
      <el-form-item label="计划类型">
        <el-radio-group
          v-model="schedule_info.schedule_type"
          @change="changeScheduleType"
        >
          <el-radio label="screen">屏幕计划</el-radio>
          <el-radio label="group">分组计划</el-radio>
        </el-radio-group>
        <!-- {{ "[" + schedule_info.id_for_screen_group + "]" }} -->
        <el-select
          v-if="schedule_info.schedule_type == 'screen'"
          style="margin-left: 20px; width: 400px"
          filterable
          v-model="schedule_info.screen_id"
          placeholder="请选择"
          @change="changeid_for_screen_group"
        >
          <el-option
            v-for="item in screen_list"
            :key="item.screen_id"
            :label="item.name"
            :value="item.screen_id"
          ></el-option>
        </el-select>
        <el-select
          v-else-if="schedule_info.schedule_type == 'group'"
          style="margin-left: 20px; width: 400px"
          filterable
          v-model="schedule_info.group_id"
          placeholder="请选择"
          @change="changeid_for_screen_group"
        >
          <el-option
            v-for="item in group_list"
            :key="item.group_id"
            :label="item.name"
            :value="item.group_id"
          ></el-option>
        </el-select>
        <!-- <label v-else >&lt;--请选择分组</label> -->
      </el-form-item>
      <el-form-item label="节目类型">
        <el-select
          v-model="schedule_info.resource_type"
          placeholder="请选择"
          @change="getFilteredScheduleByResourceType"
        >
          <el-option label="图片" value="picture"></el-option>
          <el-option label="文字" value="text"></el-option>
          <el-option label="视频" value="video"></el-option>
        </el-select>
        <el-input
          style="width: 400px; margin-left: 30px"
          placeholder="节目过滤"
          v-model.trim="query"
          @keyup.enter.native="filterResourceList2"
        ></el-input>
      </el-form-item>
      <!-- 根据 节目类型, 动态加载节目信息到列表里 -->
      <el-form-item label="节目列表" style="justify-content: center">
        <!-- <div> -->
        <el-table
          ref="multipleTable"
          :header-cell-style="{ 'text-align': 'center' }"
          :highlight-current-row="!isAdd"
          :data="filteredResourceList"
          tooltip-effect="dark"
          :stripe="true"
          height="400"
          :border="true"
          style="width: 956px; margin: 0 auto"
          @selection-change="handleSelectionChange"
          @cell-click="cellclick"
          @current-change="handleCurrentChange"
        >
          <el-table-column v-if="isAdd" type="selection" width="100">
          </el-table-column>
          <el-table-column label="节目名" show-overflow-tooltip>
            <template slot-scope="scope">{{ scope.row.name }}</template>
          </el-table-column>
          <el-table-column
            prop="url"
            label="内容/url"
            width="600"
          ></el-table-column>
        </el-table>
        <!-- </div> -->
      </el-form-item>
      <!-- {{schedule_info.play_duration}} -->
      <el-form-item label="播放时长">
        <el-input-number
          v-model="schedule_info.delay"
          style="width: 220px"
          title="播放时长:秒"
          :min="10"
          :max="1200"
        ></el-input-number>
      </el-form-item>

      <el-form-item label="播放序号">
        <el-input-number
          v-model="schedule_info.order"
          style="width: 220px"
          title="播放序号"
          placeholder="序号小的先播放"
          :min="1"
        ></el-input-number>
      </el-form-item>

      <el-form-item label="时段(开始 < 结束)">
        <!-- <el-col :span="11">
				<el-date-picker type="date" placeholder="选择日期" v-model="schedule_info.date1" style="width: 100%;">
				</el-date-picker>
			</el-col>
			<el-col class="line" :span="2">-</el-col>
			<el-col :span="11">
				<el-time-picker placeholder="选择时间" v-model="schedule_info.date2" style="width: 100%;"></el-time-picker>
			</el-col> -->
        <!-- value-format="HH:mm" -->
        <!-- default_time 数组类型 -->
        <!--  v-model="schedule_info.default_time" -->
        <el-time-picker
          :clearable="false"
          is-range
          v-model="schedule_info.default_time"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          placeholder="选择时间范围"
          :arrow-control="false"
          value-format="HH:mm:ss"
        >
        </el-time-picker>
        <el-button type="success" plain icon="el-icon-reset" @click="allDayPlay"
          >全天</el-button
        >
      </el-form-item>

      <el-form-item label="播放级别">
        <el-select v-model="schedule_info.level" placeholder="请选择">
          <el-option label="普通" value="normal"></el-option>
          <el-option label="紧急" value="top"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item class="submitdiv">
        <el-button
          circle
          plain
          icon="el-icon-back"
          title="去调度列表"
          @click="toScheduleList"
        ></el-button>
        <el-button type="primary" plain round icon="el-icon-check el-icon--left" @click="submitSchedule">{{
          isAdd ? "添加调度" : "保存调度"
        }}</el-button>
      </el-form-item>
    </el-form>
    <!-- && schedule_info.resource_type && schedule_info.resource_type !='text' -->
    <!-- 动态改变 style -->
    <div
      v-if="showMask"
      class="show-pic-mask"
      @click="showMask = false"
      :style="{
        width:
          schedule_info.resource_type == 'text'
            ? cururlForShow.width + 'px'
            : '290px',
        height:
          schedule_info.resource_type == 'text'
            ? cururlForShow.height + 'px'
            : '200px',
      }"
    >
      <img
        v-if="schedule_info.resource_type == 'picture'"
        :src="cururlForShow.url"
        alt=""
        width="100%"
        height="100%"
      />
      <video
        v-else-if="schedule_info.resource_type == 'video'"
        :src="cururlForShow.url"
        controls
        width="100%"
        height="100%"
      ></video>
      <TextShow
        v-else-if="schedule_info.resource_type == 'text'"
        :program_info="cururlForShow"
      >
      </TextShow>
    </div>
  </el-container>
</template>

<script>
import TextShow from "../components/TextShow.vue";
export default {
  name: "Schedule_edit",
  data() {
    return {
      showMask: false,
      cururlForShow: {},
      query: "",

      //修改调度:
      currentRow_for_Single: null,

      //新建调度时 ,选择的 包含多个选中的节目, 如果为空,则 禁止发送
      selectedResourceInfo: [],

      needSendSchedules: [],
      //是否新建
      isAdd: true,
      //
      schedule_info: {
        schedule_id: "",
        schedule_type: "",
        group_id: "",
        screen_id: "",
        resource_id: "",
        // resource_type:'', //新建时无此字段, 修改节目列表(类型), v-model 会增加此属性, //在修改计划时,传入的schedule_info 有此字段;
        delay: 20,
        order: 11,
        begin_time: "00:00:00",
        end_time: "23:59:59",
        level: "normal",
        // begin_time: "", //发送时, 有default_time 填充,
        // end_time: "", //
        default_time: ["00:00:00", "23:59:59"],
        // default_time: [fd, td],
      },
      //切换节目类型时, 动态请求服务器?
      filteredResourceList: [],
      //组,屏列表, 进入时刷新一次
      screen_list: [],
      group_list: [],
      resource_list: [],
    };
  },
  components: { TextShow },
  async mounted() {
    await this.refresh_screen_group_resource_list();

    if (!this.$route.params.schedule_info) return;
    console.log(
      "Schedule_edit created before",
      this.$route.params.schedule_info
    );
    this.schedule_info = this.$route.params.schedule_info;
    console.log("Schedule_edit created after", this.schedule_info);

    // this.schedule_info.program_type = ""; //需修改节目类型
    let aDefault_time = [
      this.schedule_info.begin_time,
      this.schedule_info.end_time,
    ];

    // 动态 增加对象里的一个属性, default_time, 必须通过this.$set, 才是响应式的.
    this.$set(this.schedule_info, "default_time", aDefault_time);

    aDefault_time = null;

    this.isAdd = false;
    //更新对应的节目列表
    this.getFilteredScheduleByResourceType();
  },
  methods: {
    allDayPlay() {
      this.schedule_info.default_time = ["00:00:00", "23:59:59"];
    },
    //在候选类型的节目里,继续 过滤 方便查找
    filterResourceList2() {
      this.getFilteredScheduleByResourceType();
      if (this.query)
        this.filteredResourceList = this.filteredResourceList.filter((v, i) =>
          v.name.includes(this.query)
        );
    },

    async refresh_screen_group_resource_list() {
      let ret = await this.$http.get("screens");
      const { leds } = ret.data.data;
      console.log("screens", leds);
      this.screen_list = leds;

      ret = await this.$http.get("groups");
      const { groups } = ret.data.data;
      console.log("groups", groups);
      this.group_list = groups;

      ret = await this.$http.get("resources");
      const { resources } = ret.data.data;
      console.log("resources", resources);
      this.resource_list = resources;
    },

    handleCurrentChange(row) {
      this.currentRow_for_Single = row;
      console.log("currnet row ", row);
    },

    //修改资源类型, 获取对应列表
    getFilteredScheduleByResourceType() {
      //清空 已选择的 节目列表 , 列表刷新后就为[]了
      //this.selectedResourceInfo =[]

      let w_selected_group_screen = 0;
      let h_selected_group_screen = 0;
      if (
        this.schedule_info.schedule_type == "group" &&
        this.schedule_info.group_id
      ) {
        // w_selected_group_screen = this.group_list.
        let aGroupObj = this.group_list.find(
          (v, i) => v.group_id == this.schedule_info.group_id
        );
        if (aGroupObj) {
          w_selected_group_screen = aGroupObj.width;
          h_selected_group_screen = aGroupObj.height;
        }
      } else if (
        this.schedule_info.schedule_type == "screen" &&
        this.schedule_info.screen_id
      ) {
        let aScrenObj = this.screen_list.find(
          (v, i) => v.screen_id == this.schedule_info.screen_id
        );
        if (aScrenObj) {
          w_selected_group_screen = aScrenObj.width;
          h_selected_group_screen = aScrenObj.height;
        }
      }

      console.log("w,h", w_selected_group_screen, h_selected_group_screen);

      //重新请求网络 获取 对应的节目的列表
      console.log(this.schedule_info.resource_type);
      //计算属性,watch?
      this.filteredResourceList = this.resource_list.filter((v, i) => {
        if (this.schedule_info.resource_type == "text")
          return (
            v.type == this.schedule_info.resource_type &&
            v.width == w_selected_group_screen &&
            v.height == h_selected_group_screen
          );
        else {
          return v.type == this.schedule_info.resource_type;
        }
      });

      console.log(this.filteredResourceList);
    },

    changeid_for_screen_group() {
      //改变要添加到调度里的 节目类型,
      //2021-7-23 如果 屏幕 或组的 尺寸变化了, 要不要也筛选下面的节目列表????
      this.schedule_info.resource_type = "";
    },
    changeScheduleType() {
      //console.log(this.schedule_info.schedule_type);
      //切换 计划类型时, 获取 屏幕 或分组的数据, 更新 id 和 name, size, 到 selection 里,
      //选择框 选择 就
      this.schedule_info.group_id = "";
      this.schedule_info.screen_id = "";
    },
    toScheduleList() {
      this.$router.push("/schedule_list");
    },
    async submitSchedule() {
      // 一次最多10条
      //先验证 是否所有字段都有效  ,然后发送请求,
      console.log(this.schedule_info);

      if (!this.schedule_info.schedule_type) return;
      if (
        this.schedule_info.schedule_type == "group" &&
        !this.schedule_info.group_id
      )
        return;
      if (
        this.schedule_info.schedule_type == "screen" &&
        !this.schedule_info.screen_id
      )
        return;

      //资源id 单独判断
      // if (!this.schedule_info.resource_id) return;

      if (!this.schedule_info.delay) return;
      if (!this.schedule_info.order) return;
      if (!this.schedule_info.default_time) return;
      let isok = this.timeIsOk(
        this.schedule_info.default_time[0],
        this.schedule_info.default_time[1]
      );
      if (!isok) {
        this.$message.error("开始时间必须小于结束时间");
        return;
      }
      this.schedule_info.begin_time = this.schedule_info.default_time[0];
      this.schedule_info.end_time = this.schedule_info.default_time[1];

      if (this.isAdd) {
        //多选时 一个未选
        if (this.selectedResourceInfo.length == 0) return;

        this.needSendSchedules = [];
        for (const item of this.selectedResourceInfo) {
          this.schedule_info.resource_id = item.resource_id;
          console.log("schedule_info", this.schedule_info);

          let tmpSchedule = {
            schedule_id: this.schedule_info.schedule_id,
            schedule_type: this.schedule_info.schedule_type,
            group_id: this.schedule_info.group_id,
            screen_id: this.schedule_info.screen_id,
            resource_id: this.schedule_info.resource_id,
            delay: this.schedule_info.delay,
            order: this.schedule_info.order,
            begin_time: this.schedule_info.begin_time,
            end_time: this.schedule_info.end_time,
            level: this.schedule_info.level,
          };

          this.needSendSchedules.push(tmpSchedule);
        }
        let aLen = this.needSendSchedules.length;
        if (aLen == 0) return;
        try {
          let ret = await this.$http.post("schedules", this.needSendSchedules);
          let { action, result } = ret.data.data;
          console.log(action, result);
          this.$message.success(`添加调度成功->${aLen}个`);
        } catch (error) {
          this.$message.error("添加调度失败");
        }
      } else {
        //单选 未选
        if (!this.currentRow_for_Single) return;
        this.schedule_info.resource_id = this.currentRow_for_Single.resource_id;
        // this.schedule_info.program_name =
        //   this.currentRow_for_Single.program_name;
        console.log("schedule_info", this.schedule_info);

        // 后台 api 地址未确定
        try {
          // let ret = await this.$http.post("schedules", this.schedule_info);
          let ret = await this.$http.put("schedules", this.schedule_info);
          let { action, result } = ret.data.data;
          console.log(action, result);
          this.$message.success("更新调度成功");
        } catch (error) {
          this.$message.error("更新调度失败");
        }
      }

      this.$router.push("/schedule_list");
    },
    timeIsOk(begin_time, end_time) {
      let begin = new Date("1970-01-01 " + begin_time);
      let end = new Date("1970-01-01 " + end_time);
      return begin < end;
    },
    handleSelectionChange(val) {
      this.selectedResourceInfo = val;
      console.log("seleted rows", val); // rows 数据
    },
    cellclick(row, col, cell, event) {
      // console.log(row.url,'>>>');
      // console.log(row);

      // this.showMask= this.schedule_info.resource_type && this.schedule_info.resource_type !='text'
      this.showMask =
        this.schedule_info.resource_type && this.schedule_info.resource_type;
      if (this.showMask) {
        this.cururlForShow = row;
      }
      console.log(this.cururlForShow);
      if (col.type == "selection") {
        this.$refs.multipleTable.toggleRowSelection(row);
      }
    },
  },
};
</script>

<style scoped>
/* 2021-4-27 test */
.scheduleedit {
  /* 子元素的 margin : auto  比 flex 的居中好, 子元素在某个方向上过大时, flex无法显示完全,而子的margin auto可以 */
  /* 不要上下居中了, 内容过大时 显示不全 */
  /* justify-content: center; */

  /* align-items: center; */
  height: 100%;
  /* background-color: red; */
  /* 防止小屏 显示不完全 */
  /* auto 或 scroll */
  overflow: auto;
  padding: 4px;
  /* border: 1px solid red; */
}
.scheduleedit .el-form {
  margin: auto;

  padding-top: 10px;
  /* margin-top:calc((100vh - 60px - 70px - 720px)/2); */
  /* height: 770px; */
  height: 770px;
  width: 1200px;
  background-color: rgba(234, 239, 243, 0.2);
  border: 1px dotted #aaa;
  border-radius: 10px;
  box-shadow: 0 0 10px #bbb;
  /* 2021-7-22 10->70 因大小固定,自动居中, 小屏,大屏 会有差异  */
  /* commit 2021-9-8 */
  /* padding-top: 70px; */
}

/* 2021-4-27 放到全局 app sylte 里了 */
/* .el-form-item:hover{
   border-left: 2px solid black;
} */

.el-form-item {
  margin-bottom: 10px;
}

.show-pic-mask {
  /* left: 0; */
  /* right: 0; */
  /* top: 0; */
  /* bottom: 0; */
  position: absolute;
  z-index: 100;
  background-color: rgba(0, 0, 0, 0.4);
  opacity: 0.8;
  /* 经典居中 */
  width: 290px;
  height: 200px;
  /* left: 50%; */
  left: 220px;
  top: 50%;
  /* margin-left:250px; */
  margin-top: -150px;
  border: 1px solid black;
}
</style>
